/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;

import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.domain.IndicationType;



import com.koron.hazardsource.service.api.IndicationTypeService;

import com.koron.hazardsource.util.RiskLevelDesc;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.impl.CorpManagementServiceImpl;
import com.koron.scene.domain.ProjectHazardSource;
import com.koron.scene.domain.ProjectRisk;
import com.koron.scene.mapper.ProjectHazardSourceMapper;
import com.koron.scene.mapper.ProjectRiskMapper;
import com.koron.scene.service.api.ProjectHazardSourceService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;

@Service
@PropertySource({"classpath:deviceCheckFlow.properties"})
public class ProjectHazardSourceServiceImpl implements ProjectHazardSourceService {


    private static final Logger logger = LoggerFactory.getLogger(ProjectHazardSourceServiceImpl.class);

    private static Map<RiskLevelDesc, List<Integer>> levelMap = new HashMap<>();

    static {
        levelMap.put(RiskLevelDesc.Minor, Arrays.asList(1, 2, 3, 4));
        levelMap.put(RiskLevelDesc.Ordinary, Arrays.asList(5, 6, 8, 9));
        levelMap.put(RiskLevelDesc.Serious, Arrays.asList(10, 12, 15, 16));
        levelMap.put(RiskLevelDesc.Important, Arrays.asList(20, 25));
    }

    public static final String STRING_LS = "LS";
    public static final String STRING_LEC = "LEC";

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DictDataService dataService;

    @Autowired
    private IndicationTypeService indicationTypeService;

    @Autowired
    private CorpManagementServiceImpl corpManagementService;

    @Value("${hazard_source_level_key}")
    private String hazardSourceLevelKey;

    @Override
    public MessageBean<?> delete(String sourceId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ProjectHazardSourceMapper sourceMapper = factory.getMapper(ProjectHazardSourceMapper.class);
            ProjectRiskMapper riskMapper = factory.getMapper(ProjectRiskMapper.class);
            sourceMapper.deleteByPrimaryKey(sourceId);
            riskMapper.deleteBySourceId(sourceId);
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        } finally {
            factory.close();
        }
        return msg;
    }

    @Override
    public MessageBean<?> importFromExcel(StaffBean user, MultipartFile file, String projectId, String enterpriseId, String corpCode) {
        Map<ProjectHazardSource, List<ProjectRisk>> map = new HashMap<>();
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        try {
            //先将文件上传到文件服务器
            if (null == file) {
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            String fileName = file.getOriginalFilename();
            String filePath = clientWrapper.uploadFile(file) + "#" + fileName;//文件上传的路径
            //处理excel中的内容
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            if (null == workbook) {
                logger.error("上传文件为空");
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("上传文件为空");
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            List<CellRangeAddress> combineCell = getCombineCell(sheet);
            int rowsNumm = sheet.getPhysicalNumberOfRows();
            for (int i = 4; i < rowsNumm; ) {
                XSSFRow row = sheet.getRow(i);
                // 合并了多行，取合并后单元格范围信息
                CellRangeAddress cellRange = getCellRange(combineCell, row.getCell(1));
                int lastRow = i;
                if (cellRange != null) {
                    lastRow = cellRange.getLastRow();
                }
                List<XSSFRow> rows = new ArrayList<>();
                while (lastRow >= i) {
                    rows.add(sheet.getRow(i));
                    i++;
                }
                parseRows(rows, map, user);
            }
            msg = importSubmit(filePath, user, map, projectId, enterpriseId, corpCode);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    //具体业务基本都在此方法执行
    @SuppressWarnings("unchecked")
    private MessageBean<?> importSubmit(String filePath, StaffBean user,
                                        Map<ProjectHazardSource, List<ProjectRisk>> map, String projectId, String enterpriseId, String corpCode) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        List<ProjectHazardSource> beanList = new ArrayList<>();
        try {
            //到目前为止危险源和风险等数据都是excel表中原始数据，没有添加其他属性，下面的处理中将会添加
            for (Map.Entry<ProjectHazardSource, List<ProjectRisk>> entry : map.entrySet()) {
                ProjectHazardSource lhs = entry.getKey();
                List<ProjectRisk> riskList = entry.getValue();
                if (riskList.isEmpty()) {
                    continue;
                }
                lhs.setRisks(riskList);
                lhs.setCorpCode(corpCode);
                lhs.setEnterpriseId(enterpriseId);
                lhs.setProjectId(projectId);
                beanList.add(lhs);
            }
            //保存
            msg = saveOrUpdate(beanList, user);
            return msg;
        } catch (Exception e) {
            if (!StringUtils.isEmpty(filePath)) {
                clientWrapper.deleteFile(filePath.split("#")[0]);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> saveOrUpdate(List<ProjectHazardSource> lhsList, StaffBean user) {
        MessageBean<List> msg = new MessageBean<List>();
        SessionFactory factory = new SessionFactory();
        try {
            Map checkMap = addCheck(lhsList);
            int code = (int) checkMap.get("code");
            String description = (String) checkMap.get("description");
            if (code != 0) {
                msg.setCode(code);
                msg.setDescription(description);
                factory.close(false);
                return msg;
            }
            List<String> idList = new ArrayList<String>();
            ProjectHazardSourceMapper lhsMapper = factory.getMapper(ProjectHazardSourceMapper.class);
            ProjectRiskMapper lrMapper = factory.getMapper(ProjectRiskMapper.class);
            Date date = new Date();
            for (ProjectHazardSource lhs : lhsList) {
                List<ProjectRisk> lrList = lhs.getRisks();
                if (lhs.getState() == null) {
                    lhs.setState(1);
                }
                if (lhs.getFitAllBusiness()) {
                    lhs.setBusinessTypeId(null);
                }
                lhs.setAddTime(date);
                lhs.setAddUser(user.getCode());
                lhs.setAddUserName(user.getName());
                lhs.setUpdateTime(date);
                lhs.setUpdateUser(user.getCode());
                lhs.setUpdateUserName(user.getName());
                lhs.setFstatusflag(2);
                lhs.setState(1);
                String id = lhs.getId();
                if (lhs.getTemplateCode() == null) {
                    lhs.setExclusive(0);
                } else {
                    lhs.setExclusive(1);
                }
                if (StringUtils.isEmpty(id)) {
                    //新增
                    id = DefaultIdGenerator.getInstance().generateLongId();
                    lhs.setId(id);
//                    lhs.setCode(generateCode(factory, lhs));
                    for (ProjectRisk lr : lrList) {
                        BaseEntityUtil.setAddBaseProperties(lr, user);
                        lr.setLocalHazardId(id);
                    }
                    lhsMapper.insert(lhs);
                    lrMapper.batchInsert(lrList);
                } else {
                    lrMapper.deleteBySourceId(id);
                    for (ProjectRisk lr : lrList) {
                        BaseEntityUtil.setAddBaseProperties(lr, user);
                        lr.setLocalHazardId(id);
                    }
                    lhsMapper.updateByPrimaryKeySelective(lhs);
                    lrMapper.batchInsert(lrList);
                }
                idList.add(id);
            }
            factory.close();
            msg.setCode(0);
            msg.setDescription("保存成功");
            msg.setData(idList);
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    public void setProperties(List<ProjectHazardSource> list) {
        try (SessionFactory factory = new SessionFactory()) {
            Map<String, String> corpMap = corpManagementService.getCodeNameMap();
            for (ProjectHazardSource lhs : list) {
                ProjectRiskMapper riskMapper = factory.getMapper(ProjectRiskMapper.class);
                List<ProjectRisk> lrList = riskMapper.queryBySourceId(lhs.getId());
                Integer temp = 0;
                String levelName = "";
                for (ProjectRisk lr : lrList) {
                    RiskLevelDesc levelDesc = match(lr.getRiskLevel());
                    lr.setRiskLevelName(levelDesc != null ? levelDesc.getName() : "");
                    levelDesc = match(lr.getResidueLevel());
                    lr.setResidueLevelName(levelDesc != null ? levelDesc.getName() : "");
                    Integer level = lr.getRiskLevel() == null ? 0 : lr.getRiskLevel();
                    if (level > temp) {
                        temp = level;
                        levelName = lr.getRiskLevelName();
                    }
                }
                lhs.setRisks(lrList);
                if (temp != 0) {
                    lhs.setRiskLevel(temp);
                    lhs.setRiskLevelName(levelName);
                }
                String corpName = corpMap.get(lhs.getCorpCode());
                if (corpName == null) {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(lhs.getCorpCode());
                    if (corpBean != null) {
                        corpName = corpBean.getCorpName();
                        corpMap.put(lhs.getCorpCode(), corpName);
                    }
                }
                lhs.setCorpName(corpName);
            }
        }
    }

    @Override
    public MessageBean<?> list(StaffBean user, String projectId, String enterpriseId, String name, String corpCode, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory();) {
            Integer start = null;
            Integer totalPage = null;
            Integer totalNumber = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            ProjectHazardSourceMapper mapper = factory.getMapper(ProjectHazardSourceMapper.class);
            List<ProjectHazardSource> list = mapper.queryList(projectId, enterpriseId, name, corpCode, start, pageSize, null, null, null);
            if (list != null && list.size() > 0) {
                setProperties(list);
            }
            totalNumber = mapper.queryListTotal(projectId, enterpriseId, name, corpCode, null, null, null);
            if (start != null && pageSize != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(list);
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> exportList(StaffBean user, String projectId, String enterpriseId, String name, String corpCode) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory();) {

            ProjectHazardSourceMapper mapper = factory.getMapper(ProjectHazardSourceMapper.class);
            List<ProjectHazardSource> list = mapper.queryList(projectId, enterpriseId, name, corpCode, null, null, null, null, null);
            if (list != null && list.size() > 0) {
                setProperties(list);
            }
            msg.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    private Map addCheck(List<ProjectHazardSource> lhsList) {
        Map map = new HashMap();
        for (ProjectHazardSource lhs : lhsList) {
            if (null == lhs) {
                map.put("code", 32002);
                map.put("description", "未填写危险源信息无法保存");
                return map;
            }
            List<ProjectRisk> lrList = lhs.getRisks();
            if (null == lrList) {
                map.put("code", 32002);
                map.put("description", "未填写危险源的风险项信息无法保存");
                return map;
            }
            //校验危险源的字段
            if (StringUtils.isEmpty(lhs.getName())) {
                map.put("code", 32002);
                map.put("description", "危险源名称不能为空");
                return map;
            }
            if (!lhs.getFitAllBusiness()) {
                if (StringUtils.isEmpty(lhs.getBusinessTypeId())) {
                    map.put("code", 22001);
                    map.put("description", "非通用，危险源业态不能为空");
                    return map;
                }
            }
            if (StringUtils.isBlank(lhs.getCorpCode())) {
                if (StringUtils.isEmpty(lhs.getBusinessTypeId())) {
                    map.put("code", 22001);
                    map.put("description", "公司code不能为空");
                    return map;
                }
            }
            if (StringUtils.isEmpty(lhs.getHazardTypeId())) {
                map.put("code", 32002);
                map.put("description", "危险源类型不能为空");
                return map;
            }
            if (StringUtils.isEmpty(lhs.getProjectId())) {
                map.put("code", 32002);
                map.put("description", "项目不能为空");
                return map;
            }
            if (StringUtils.isEmpty(lhs.getEnterpriseId())) {
                map.put("code", 32002);
                map.put("description", "相关方不能为空");
                return map;
            }
            //校验风险的字段
            for (ProjectRisk lr : lrList) {
                if (StringUtils.isEmpty(lr.getRiskInfo())) {
                    map.put("code", 32002);
                    map.put("description", "风险列表中存在风险描述为空");
                    return map;
                }
                if (StringUtils.isEmpty(lr.getAccidentTypeId())) {
                    map.put("code", 32002);
                    map.put("description", "风险列表中存在风险事故类型为空");
                    return map;
                }
                if (StringUtils.isEmpty(lr.getRiskReason())) {
                    map.put("code", 32002);
                    map.put("description", "风险列表中存在风险原因描述为空");
                    return map;
                }
                if (null == lr.getPossibility()) {
                    if (STRING_LS.equals(lhs.getIdentificationType())) {
                        map.put("code", 32002);
                        map.put("description", "风险列表中存在风险可能性为空");
                        return map;
                    } else if (STRING_LEC.equals(lhs.getIdentificationType())) {
                        lr.setPossibility(0);
                    }
                }
                if (null == lr.getSeverity()) {
                    if (STRING_LS.equals(lhs.getIdentificationType())) {
                        map.put("code", 32002);
                        map.put("description", "风险列表中存在风险项严重性为空");
                        return map;
                    } else if (STRING_LEC.equals(lhs.getIdentificationType())) {
                        lr.setSeverity(0);
                    }
                }
                //计算风险等级
                lr.setRiskLevel(lr.getPossibility() * lr.getSeverity());
                RiskLevelDesc levelDesc = match(lr.getRiskLevel());
                lr.setControlLevel(levelDesc != null ? levelDesc.getControlDesc() : "");

                if (lr.getResiduePossibility() != null && lr.getResidueSeverity() != null) {
                    //残余风险等级
                    lr.setResidueLevel(lr.getResiduePossibility() * lr.getResidueSeverity());
                    levelDesc = match(lr.getResidueLevel());
                    lr.setResidueControlLevel(levelDesc != null ? levelDesc.getControlDesc() : "");
                }
            }

        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;

    }

    private ProjectHazardSource parseHazardSource(XSSFRow row, StaffBean user) {
        ProjectHazardSource lhs = new ProjectHazardSource();
        lhs.setFitAllBusiness(true);
        String sourceName = getCellValue(row.getCell(1));
        String fitAll = getCellValue(row.getCell(2));
        if (StringUtils.isEmpty(fitAll)) {
            fitAll = "n";
        }
        if (fitAll.equalsIgnoreCase("否") || fitAll.equalsIgnoreCase("n") || fitAll.equalsIgnoreCase("no")) {
            lhs.setFitAllBusiness(false);
            String businessTypeName = getCellValue(row.getCell(3));
            if (StringUtils.isEmpty(businessTypeName)) {
                return null;
            }
            DictData businessTypeItem = dataService.matchDictData("业态", businessTypeName);
            if (businessTypeItem == null) {
                return null;
            }
            lhs.setBusinessTypeId(businessTypeItem.getId());
            lhs.setBusinessTypeName(businessTypeName);
        }

        String hazardTypeName = getCellValue(row.getCell(4));
        if (StringUtils.isEmpty(sourceName) || StringUtils.isEmpty(hazardTypeName)) {
            return null;
        }

        DictData hazardTypeItem = dataService.matchDictData("危险源类型", hazardTypeName);
        if (hazardTypeItem == null) {
            return null;
        }

        IndicationType indicationType = indicationTypeService.fetchForKey("hazardsource_level_type");
        String indicationLevelName = getCellValue(row.getCell(5));
        if (StringUtils.isEmpty(indicationLevelName) || StringUtils.isEmpty(indicationLevelName)) {
            lhs.setIndicationLevelId(indicationType.getIndicationItems().get(0).getId());
        } else {
            boolean flag = false;
            for (IndicationItems indication : indicationType.getIndicationItems()) {
                if (indication.getName().equalsIgnoreCase(indicationLevelName)) {
                    lhs.setIndicationLevelId(indication.getId());
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                lhs.setIndicationLevelId(indicationType.getIndicationItems().get(0).getId());
            }
        }
        lhs.setName(sourceName);
        lhs.setHazardTypeId(hazardTypeItem.getId());
        lhs.setHazardTypeName(hazardTypeName);
        // 导入的code
        lhs.setCode(getCellValue(row.getCell(0)));
        return lhs;
    }

    private ProjectRisk parseRisk(XSSFRow row) {
        String accidentTypeName = getCellValue(row.getCell(6));
        DictData accidentTypeItem = dataService.matchDictData("事故类型", accidentTypeName);
        if (accidentTypeItem == null) {
            return null;
        }
        ProjectRisk lr = new ProjectRisk();
        lr.setRiskInfo(getCellValue(row.getCell(7)));
        lr.setRiskReason(getCellValue(row.getCell(8)));
        lr.setAccidentTypeId(accidentTypeItem.getId());
        lr.setPossibility((int) Double.parseDouble(getCellValue(row.getCell(9))));
        lr.setSeverity((int) Double.parseDouble(getCellValue(row.getCell(10))));
        lr.setPrecaution(getCellValue(row.getCell(13)));
        try {
            Integer residuePossibility = (int) Double.parseDouble(getCellValue(row.getCell(14)));
            Integer residueSeverity = (int) Double.parseDouble(getCellValue(row.getCell(15)));
            lr.setResiduePossibility(residuePossibility);
            lr.setResidueSeverity(residueSeverity);
        } catch (NumberFormatException e) {
            logger.error(e.getMessage(),e);
        }
        return lr;
    }

    private RiskLevelDesc match(Integer riskLevel) {
        if (riskLevel != null) {
            for (Map.Entry<RiskLevelDesc, List<Integer>> entry : levelMap.entrySet()) {
                RiskLevelDesc key = entry.getKey();
                List<Integer> value = entry.getValue();
                if (value.contains(riskLevel)) {
                    return key;
                }
            }
        }
        return null;
    }

    // 单个危险源和多个风险
    private String parseRows(List<XSSFRow> rows, Map<ProjectHazardSource, List<ProjectRisk>> map, StaffBean user)
            throws Exception {
        ProjectHazardSource phs = new ProjectHazardSource();
        List<ProjectRisk> riskList = new ArrayList<>();
        StringBuilder description = new StringBuilder();
        for (int i = 0; i < rows.size(); i++) {
            if (i == 0) {
                phs = parseHazardSource(rows.get(i), user);
                if (phs == null) {
                    return null;
                }
            }
            ProjectRisk risk = parseRisk(rows.get(i));
            if (risk != null) {
                riskList.add(risk);
            }
        }
        if (!riskList.isEmpty()) {
            map.put(phs, riskList);
        }
        return description.toString();

    }


    /**
     * 获取合并单元格的范围
     *
     * @param listCombineCell
     * @param cell
     * @return
     */
    private CellRangeAddress getCellRange(List<CellRangeAddress> listCombineCell, XSSFCell cell) {
        int firstC = 0, lastC = 0, firstR = 0, lastR = 0;
        for (CellRangeAddress ca : listCombineCell) {
            // 获得合并单元格的起始行, 结束行, 起始列, 结束列
            firstC = ca.getFirstColumn();
            lastC = ca.getLastColumn();
            firstR = ca.getFirstRow();
            lastR = ca.getLastRow();
            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
                    return ca;
                }
            }
        }
        return null;
    }

    /**
     * 合并单元格处理,获取合并行
     *
     * @param sheet
     * @return List<CellRangeAddress>
     */
    public List<CellRangeAddress> getCombineCell(XSSFSheet sheet) {
        List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
        // 获得一个 sheet 中合并单元格的数量
        int sheetmergerCount = sheet.getNumMergedRegions();
        // 遍历所有的合并单元格
        for (int i = 0; i < sheetmergerCount; i++) {
            // 获得合并单元格保存进list中
            CellRangeAddress ca = sheet.getMergedRegion(i);
            list.add(ca);
        }
        return list;
    }

    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getCellValue(XSSFCell cell) {
        if (cell == null)
            return "";
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }


    public String generateCode(SessionFactory factory, ProjectHazardSource lhs) {
        String convert = "";
        CorpManagementMapper corpMapper = factory.getMapper(CorpManagementMapper.class);
        CorpBean corpBean = corpMapper.get(lhs.getCorpCode());
        if (corpBean == null) {
            convert = "#####";
        }
        convert = corpBean.getShortCode();
        if (StringUtils.isEmpty(convert)) {
            convert = "#####";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("W");
        Integer count = 0;
        if (StringUtils.isEmpty(lhs.getTemplateCode())) {
            Boolean all = lhs.getFitAllBusiness();
            ProjectHazardSourceMapper mapper = factory.getMapper(ProjectHazardSourceMapper.class);
            if (all) {
                count = mapper.queryListTotal(null, null, null, lhs.getCorpCode(), null, null, all);
                sb.append("C");
            } else {
                String businessValue = "";
                String hazardValue = "";
                DictDataMapper ddMapper = factory.getMapper(DictDataMapper.class);
                DictData businessType = ddMapper.queryOne(lhs.getBusinessTypeId());
                if (businessType != null) {
                    businessValue = businessType.getDictValue();
                }
                DictData hazardType = ddMapper.queryOne(lhs.getHazardTypeId());
                if (hazardType != null) {
                    hazardValue = hazardType.getDictValue();
                }
                sb.append(businessValue).append(hazardValue);
                count = mapper.queryListTotal(null, null, null, lhs.getCorpCode(), lhs.getBusinessTypeId(), lhs.getHazardTypeId(), null);
            }
            count++;
            NumberFormat nf = NumberFormat.getInstance();
            nf.setGroupingUsed(false);
            nf.setMaximumIntegerDigits(3); // 设置最大整数位数
            nf.setMinimumIntegerDigits(3); // 设置最小整数位数
            sb.append(nf.format(count));
        } else {
            sb.append(lhs.getTemplateCode());
        }
        sb.append("-").append(convert);
        return sb.toString();
    }
}
